﻿using System;
using System.Linq;
using Biz.Buffer;
using Biz.EF.Gateway.Monitor;
using Biz.EF.Platform;
using Hjt212Parser;
using log4net;

namespace Biz.Process
{
    public class DownlineCmdInstructionTotal
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(DownlineCmdInstructionTotal));
        private static string _CardTypeAdmin = "管理";
        private static string _CardTypeMaintain = "运维";

        public static void Gen3051_3071CmdToGateway(GatewayMonitorContext gCtx, PlatformContext pCtx)
        {
            try
            {
                var cmds = pCtx.反控阀门.Where(t => t.执行结果标志ID == 601).Take(1000).ToList();
                foreach (var downcmd in cmds)
                {
                    downcmd.执行结果标志ID = 602;
                    if (string.IsNullOrEmpty(downcmd.QN))
                    {
                        downcmd.QN = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    }
                    var cn = "";
                    switch (downcmd.阀门执行事项ID)
                    {
                        case 301:
                            cn = "3051";
                            break;
                        case 302:
                            cn = "3071";
                            break;
                    }
                    var port = CommonInformation.GetLetportById(downcmd.设备信息ID);
                    if (string.IsNullOrEmpty(port?.工控机编号MN)) continue;
                    var cp = "";
                    if (cn.Equals("3051"))
                    {
                        cp = "Per=" + (downcmd.阀门状态.Contains("开") ? "100" : "000");
                    }
                    var resultStr = "QN=" + downcmd.QN + ";ST=32;" + "CN=" + cn + ";PW=123456" + ";MN=" + port.工控机编号MN
                                        + ";Flag=5;CP=&&" + cp + "&&";
                    var result = Crc.WrapByCrc(resultStr, "monitor");
                    var now = DateTime.Now;
                    send_ctr_cmd cmd = new send_ctr_cmd
                    {
                        cn = cn,
                        mn = port.工控机编号MN,
                        qn = downcmd.QN,
                        is_sent = false,
                        send_string = result,
                        sent_time = now,
                        send_time = now
                    };
                    gCtx.send_ctr_cmd.Add(cmd);
                    gCtx.SaveChanges();
                }
                pCtx.SaveChanges();
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }

        }

        public static void Gen3094CmdToGateway(GatewayMonitorContext gCtx, PlatformContext pCtx)
        {
            try
            {
                var cmds = pCtx.许可证main.Where(t => t.执行结果标志ID == 601).Take(1000).ToList();
                foreach (var downcmd in cmds)
                {
                    downcmd.执行结果标志ID = 602;
                    if (downcmd.设备信息ID == null) continue;
                    if (string.IsNullOrEmpty(downcmd.QN))
                    {
                        downcmd.QN = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    }
                    var port = CommonInformation.GetLetportById(downcmd.设备信息ID.Value);
                    if (!string.IsNullOrEmpty(port?.工控机编号MN))
                    {
                        var cp = "";

                        var details = downcmd.许可证detail;
                        foreach (var detail in details)
                        {
                            var factor = CommonInformation.GetFactorById(detail.污染物编码ID);
                            if (factor == null) continue;
                            cp += factor.污染物代码.Trim() + "-DayAll=" + (detail.污染物日排放量 ?? 0) +
                                  "," + factor.污染物代码.Trim() + "-YeaAll=" + (detail.污染物年排放量 ?? 0)
                                  + "," + factor.污染物代码.Trim() + "-Rtd=" + (detail.污染物浓度 ?? 0);
                            cp += ";";
                        }
                        var resultStr = "QN=" + downcmd.QN + ";ST=32;" + "CN=3094" + ";PW=123456" + ";MN=" +
                                        port.工控机编号MN
                                        + ";Flag=5;CP=&&" + cp + "&&";
                        resultStr = resultStr.Replace(";&&", "&&");
                        var result = Crc.WrapByCrc(resultStr, "monitor");
                        var now = DateTime.Now;
                        send_ctr_cmd cmd = new send_ctr_cmd
                        {
                            cn = "3094",
                            mn = port.工控机编号MN,
                            qn = downcmd.QN,
                            is_sent = false,
                            send_string = result,
                            sent_time = now,
                            send_time = now
                        };
                        gCtx.send_ctr_cmd.Add(cmd);
                        gCtx.SaveChanges();
                    }


                    if (!string.IsNullOrEmpty(port?.企业端数采MN))
                    {
                        var cp = "";

                        var details = downcmd.许可证detail;
                        foreach (var detail in details)
                        {
                            var factor = CommonInformation.GetFactorById(detail.污染物编码ID);
                            if (factor == null) continue;
                            cp += factor.污染物代码.Trim() + "-UpLimit=" + (detail.污染物浓度 ?? 0);
                            cp += ";";
                        }
                        var resultStr = "QN=" + downcmd.QN + ";ST=32;" + "CN=3194" + ";PW=123456" + ";MN=" +
                                        port.企业端数采MN
                                        + ";Flag=5;CP=&&" + cp + "&&";
                        resultStr = resultStr.Replace(";&&", "&&");
                        var result = Crc.WrapByCrc(resultStr, "monitor");
                        var now = DateTime.Now;
                        send_ctr_cmd cmd = new send_ctr_cmd
                        {
                            cn = "3194",
                            mn = port.企业端数采MN,
                            qn = downcmd.QN,
                            is_sent = false,
                            send_string = result,
                            sent_time = now,
                            send_time = now
                        };
                        gCtx.send_ctr_cmd.Add(cmd);
                        gCtx.SaveChanges();
                    }


                    if (!string.IsNullOrEmpty(port?.企业端数采二MN))
                    {
                        var cp = "";

                        var details = downcmd.许可证detail;
                        foreach (var detail in details)
                        {
                            var factor = CommonInformation.GetFactorById(detail.污染物编码ID);
                            if (factor == null) continue;
                            cp += factor.污染物代码.Trim() + "-UpLimit=" + (detail.污染物浓度 ?? 0);
                            cp += ";";
                        }
                        var resultStr = "QN=" + downcmd.QN + ";ST=32;" + "CN=3194" + ";PW=123456" + ";MN=" +
                                        port.企业端数采二MN
                                        + ";Flag=5;CP=&&" + cp + "&&";
                        resultStr = resultStr.Replace(";&&", "&&");
                        var result = Crc.WrapByCrc(resultStr, "monitor");
                        var now = DateTime.Now;
                        send_ctr_cmd cmd = new send_ctr_cmd
                        {
                            cn = "3194",
                            mn = port.企业端数采二MN,
                            qn = downcmd.QN,
                            is_sent = false,
                            send_string = result,
                            sent_time = now,
                            send_time = now
                        };
                        gCtx.send_ctr_cmd.Add(cmd);
                        gCtx.SaveChanges();
                    }
                }
                pCtx.SaveChanges();
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }

        }

        public static void Gen3097CmdToGateway(GatewayMonitorContext gCtx, PlatformContext pCtx)
        {
            try
            {
                var cmds = pCtx.反控门禁.Where(t => t.执行结果标志ID == 601)
                    .Where(t => t.执行事项ID != null && t.执行事项ID == 1201)
                    .Take(1000).ToList();
                foreach (var downcmd in cmds)
                {
                    downcmd.执行结果标志ID = 602;
                    if (string.IsNullOrEmpty(downcmd.QN))
                    {
                        downcmd.QN = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    }
                    var port = CommonInformation.GetLetportById(downcmd.设备信息ID);
                    if (string.IsNullOrEmpty(port?.工控机编号MN)) continue;

                    var resultStr = "QN=" + downcmd.QN + ";ST=32;" + "CN=3097;PW=123456" + ";MN=" + port.工控机编号MN
                                        + ";Flag=5;CP=&&Gate=ON&&";
                    var result = Crc.WrapByCrc(resultStr, "monitor");
                    var now = DateTime.Now;
                    send_ctr_cmd cmd = new send_ctr_cmd
                    {
                        cn = "3097",
                        mn = port.工控机编号MN,
                        qn = downcmd.QN,
                        is_sent = false,
                        send_string = result,
                        sent_time = now,
                        send_time = now
                    };
                    gCtx.send_ctr_cmd.Add(cmd);
                    gCtx.SaveChanges();
                }
                pCtx.SaveChanges();
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }

        }

        public static void Gen3091CmdToGateway(GatewayMonitorContext gCtx, PlatformContext pCtx)
        {
            try
            {
                var cmds = pCtx.远程充值.Where(t => t.执行结果标志ID == 601).Take(1000).ToList();
                foreach (var downcmd in cmds)
                {
                    downcmd.执行结果标志ID = 602;
                    if (string.IsNullOrEmpty(downcmd.QN))
                    {
                        downcmd.QN = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    }
                    var port = CommonInformation.GetLetportById(downcmd.设备信息ID);
                    if (string.IsNullOrEmpty(port?.工控机编号MN)) continue;
                    var all = pCtx.远程充值.Where(t => t.设备信息ID == downcmd.设备信息ID).Sum(t => t.充值量);
                    var resultStr = "QN=" + downcmd.QN + ";ST=32;" + "CN=3091;PW=123456" + ";MN=" + port.工控机编号MN
                                        + ";Flag=5;CP=&&Month=" + downcmd.操作时间.ToString("yyyyMM")
                                        + ";w00000-Charge-Month=" + downcmd.充值量
                                         + ";w00000-Charge-All=" + all
                                        + "&&";
                    var result = Crc.WrapByCrc(resultStr, "monitor");
                    var now = DateTime.Now;
                    send_ctr_cmd cmd = new send_ctr_cmd
                    {
                        cn = "3091",
                        mn = port.工控机编号MN,
                        qn = downcmd.QN,
                        is_sent = false,
                        send_string = result,
                        sent_time = now,
                        send_time = now
                    };
                    gCtx.send_ctr_cmd.Add(cmd);
                    gCtx.SaveChanges();
                }
                pCtx.SaveChanges();
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }

        }

        public static void Gen5012CmdToGatewayOld(GatewayMonitorContext gCtx, PlatformContext pCtx)
        {
            try
            {
                var admin = pCtx.IcCards.Where(t => t.Enabled).FirstOrDefault(t => t.CardType.Contains(_CardTypeAdmin));
                if (admin == null)
                {
                    Log.Debug("没有管理卡！");
                    return;
                }
                var maintain = pCtx.IcCards.Where(t => t.Enabled).FirstOrDefault(t => t.CardType.Contains(_CardTypeMaintain));
                if (maintain == null)
                {
                    Log.Debug("没有运维卡！");
                    return;
                }
                var cmds = pCtx.IcCards
                    //.Where(t=>t.EnterpriseId!=null)
                    .Where(t => t.Enabled)
                    .Where(t => !(t.CardType.Contains(_CardTypeAdmin) || t.CardType.Contains(_CardTypeMaintain)))
                    .Where(t => !t.IsSynchronized)
                    .Take(1000)
                    .ToList();
                foreach (var downcmd in cmds)
                {
                    if (string.IsNullOrEmpty(downcmd.Qn))
                    {
                        downcmd.Qn = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                    }
                    if (downcmd.EnterpriseId != null)
                    {
                        var port = CommonInformation.GetLetportById(downcmd.EnterpriseId.Value);
                        if (string.IsNullOrEmpty(port?.工控机编号MN)) continue;

                        var resultStr = "QN=" + downcmd.Qn + ";ST=32;" + "CN=5012;PW=123456" + ";MN=" + port.工控机编号MN
                                        + ";Flag=5;CP=&&AdminCardNo=" + admin.CardNo
                                        + ";MaintainCardNo=" + maintain.CardNo
                                        + ";EnterpriseCardNo=" + downcmd.CardNo
                                        + "&&";
                        var result = Crc.WrapByCrc(resultStr, "monitor");
                        var now = DateTime.Now;
                        send_ctr_cmd cmd = new send_ctr_cmd
                        {
                            cn = "5012",
                            mn = port.工控机编号MN,
                            qn = downcmd.Qn,
                            is_sent = false,
                            send_string = result,
                            sent_time = now,
                            send_time = now
                        };
                        gCtx.send_ctr_cmd.Add(cmd);
                    }
                    gCtx.SaveChanges();
                    downcmd.IsSynchronized = true;
                }
                pCtx.SaveChanges();
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }

        }
        public static void Gen5012CmdToGatewayAdminAndMaintain(GatewayMonitorContext gCtx, PlatformContext pCtx)
        {
            try
            {
                Gen5012CmdToGatewayAdminOrMaintain(gCtx, pCtx);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
            }

        }

        private static void Gen5012CmdToGatewayAdminOrMaintain(GatewayMonitorContext gCtx, PlatformContext pCtx)
        {

            var qn = "";
            var now4Qn = DateTime.Now;
            var admins = pCtx.IcCards.Where(t => !t.IsSynchronized).Where(t => t.Enabled).Where(t => t.CardType.Contains(_CardTypeAdmin)).ToList();
            if (admins.Count < 1) return;
            var adminCards = "";

            foreach (var admin in admins)
            {
                if (string.IsNullOrEmpty(admin.Qn))
                {
                    admin.Qn = now4Qn.ToString("yyyyMMddHHmmssfff");
                }
                admin.IsSynchronized = true;
                qn = admin.Qn;
                if (!string.IsNullOrEmpty(admin.CardNo))
                    adminCards = admin.CardNo;
            }

            var maintains = pCtx.IcCards.Where(t => !t.IsSynchronized).Where(t => t.Enabled).Where(t => t.CardType.Contains(_CardTypeMaintain)).ToList();
            if (maintains.Count < 1) return;
            var maintainCards = "";
            foreach (var maintain in maintains)
            {
                if (string.IsNullOrEmpty(maintain.Qn))
                {
                    maintain.Qn = now4Qn.ToString("yyyyMMddHHmmssfff");
                }
                maintain.IsSynchronized = true;
                qn = maintain.Qn;
                if (!string.IsNullOrEmpty(maintain.CardNo))
                    maintainCards = maintain.CardNo;
            }


            var enterprises = pCtx.EnterpriseInfors.ToList();
            foreach (var enterprise in enterprises)
            {
                var port = CommonInformation.GetLetportById(enterprise.ID);
                if (string.IsNullOrEmpty(port?.工控机编号MN)) continue;

                var resultStr = "QN=" + qn + ";ST=32;" + "CN=5012;PW=123456" + ";MN=" + port.工控机编号MN
                                + ";Flag=5;CP=&&AdminCardNo=" + adminCards
                                + ";MaintainCardNo=" + maintainCards
                                + ";EnterpriseCardNo="
                                + "&&";
                var result = Crc.WrapByCrc(resultStr, "monitor");
                var now = DateTime.Now;
                send_ctr_cmd cmd = new send_ctr_cmd
                {
                    cn = "5012",
                    mn = port.工控机编号MN,
                    qn = qn,
                    is_sent = false,
                    send_string = result,
                    sent_time = now,
                    send_time = now
                };
                gCtx.send_ctr_cmd.Add(cmd);
                gCtx.SaveChanges();

                //admin.DisableReason = "等待回复";
            }
            pCtx.SaveChanges();
        }


    }
}
